package cn.com.coding.app;

import cn.com.coding.common.lang.Const;
import cn.com.coding.common.lang.ResT;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Api(tags = "验证码")
@RestController

public class AuthController extends BaseController {

    @Autowired
    private Producer producer;

    @GetMapping("/captcha")
    public ResT captcha() throws IOException {

        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        // 为了测试
//        key = "aaaaa";
//        code = "1";

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        // 转Base64格式
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 1200);

        return ResT.ok().setData(MapUtil.builder().put("token", key).put("captchaImg", base64Img).build());
    }

    /**
     * 获取用户信息接口
     *
     * @param principal
     * @return
     */
//    @GetMapping("/sys/userInfo")
//    public ResT userInfo(Principal principal) {
//
//        SysUserEntity sysUser = sysUserService.getByUsername(principal.getName());
//
//        return ResT.ok().setData(MapUtil.builder()
//                .put("id", sysUser.getPid())
//                .put("username", sysUser.getUsername())
//                .put("avatar", sysUser.getAvatar())
//                .put("created", sysUser.getCreateTime())
//                .map());
//    }


}
